package com.schedule.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.schedule.common.BaseContext;
import com.schedule.common.R;
import com.schedule.dto.EventDto;
import com.schedule.entity.Event;
import com.schedule.mapper.EventMapper;
import com.schedule.service.EventService;
import com.sun.media.sound.RIFFReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/event")
public class EventController {
    @Autowired
    private EventService eventService;
    @Autowired
    private EventMapper eventMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增事件
     * @param event
     * @return
     */
    @PostMapping("/save")
    public R<Event> save(@RequestBody Event event){

        //日志
        log.info(event.toString());

        return eventService.saveEvent(event);


    }

    @PostMapping("/update")
    public R<Event> update(@RequestBody Event event){
        //日志
        log.info("开始对事件进行更新,{}",event.toString());

//        String yearMonth = event.getStartTime().getYear()+"-"+event.getStartTime().getMonth();
//        //动态设置key
//        String key="calender_userId_"+event.getUserId()+"_yearMonth_"+yearMonth;
//        redisTemplate.delete(key);

        eventService.updateById(event);

        return R.success(event);
    }

    /**
     * 根据条件查询事件列表 (user_id,start_date)
     * @param event
     * @return
     * @throws IOException
     */
    @PostMapping("/list")
    public R<List<Event>> list(@RequestBody EventDto event)  {
        log.info("开始返回事件列表,{}",event.toString());
        List<Event> events = eventService.listByCondition(event);
        return R.success(events);
    }

    /**
     * 随机返回一个事件
     * @param id
     * @return
     */
    @GetMapping("/random")
    public R<Event> random(Long id){
        //获得该用户所有事件，返回随机列表
        List<Event> events = eventMapper.orderByRand(id);

        if (events.isEmpty())
            return R.error("当前用户没有任何事件");
        return R.success(events.get(0));
    }

    /**
     * 根据条件删除事件,目前只根据id
     * @param event
     * @return
     */
    @PostMapping("/delete")
    public R<String> del(@RequestBody Event event){
        boolean del = eventService.delByCondition(event);
        if (!del)
            return R.error("删除失败");
        return R.success("删除成功");
    }

    @PostMapping("/calendar")
    public R<List<List<Event>>> calendar(@RequestBody EventDto eventDto){
        return R.success(eventService.calendar(eventDto));
    }
}
